package com.csun.cmny.provider.device.radar;

import com.csun.cmny.mqtt.utils.JsonUtil;
import com.csun.cmny.provider.utils.DateUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2021/6/7 13:27
 * @Description: TODO
 */
@Slf4j
@Component
public class RadarPub {

    private String url = "tcp://47.104.3.68:1883";
    private String clientid = "radar";
    public MqttClient client;

    public static Map<String, RadarData> data = Maps.newConcurrentMap();

    public RadarPub() throws MqttException {

        // 连接
        connect();
    }

    public void connect() {

        try {

            if (client == null) {
                client = new MqttClient(url, clientid, new MemoryPersistence());
            }

            MqttConnectOptions options = new MqttConnectOptions();
            // 保留会话
            options.setCleanSession(true);
            /**
             * 不需要用户名和密码
             */
            //options.setUserName(username);
            //options.setPassword(password.toCharArray());
            // 设置回调
            client.setCallback(new PushCallback());
            options.setConnectionTimeout(30);
            options.setKeepAliveInterval(60);

            if (!client.isConnected()) {
                client.connect(options);
            } else {
                client.disconnect();
                client.connect(options);
            }
//            client.subscribe(topic, qos);

        } catch (Exception e) {
            log.error("====> mqtt publish error = {}", e.getMessage());
        }
    }

    public boolean publish(MqttTopic topic, MqttMessage message)
            throws MqttPersistenceException, MqttException {

        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();

        log.info("publish to topic = {}, msg = {}, result = {}",
                topic.getName(), new String(message.getPayload()),
                token.isComplete());

        return token.isComplete();
    }

    public void sendMessage(String topic, Object message) {

        /* mqtt 主题 */
        MqttTopic mqttTopic = client.getTopic(topic);
        /* mqtt 消息 */
        MqttMessage mqttMsg = new MqttMessage();
        /* mqtt 消息质量 */
        mqttMsg.setQos(0);
        /* mqtt 消息是否保持 */
        mqttMsg.setRetained(false);
        /* mqtt 消息内容 */
        mqttMsg.setPayload(JsonUtil.getInfoMap(message).getBytes());
        try {
            /* mqtt client 发布消息 */
            publish(mqttTopic, mqttMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private class PushCallback implements MqttCallback {
        @Override
        public void connectionLost(Throwable throwable) {
            System.out.println("connectionLost: " + throwable.getMessage());
        }
        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            System.out.println("接收消息主题:" + topic);
            System.out.println("接收消息Qos:" + message.getQos());
            System.out.println("接收消息内容:" + new String(message.getPayload()));
        }
        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            System.out.println("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
        }
    }
}
